import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export async function GET() {
  try {
    const tokens = await prisma.memeToken.findMany({
      where: { isActive: true },
      include: {
        strategy: true,
        priceData: {
          orderBy: { timestamp: 'desc' },
          take: 1
        }
      }
    });

    // 返回数据库中的代币，使用最新的价格数据
    const tokensWithPrice = tokens.map((token) => {
      const latestPrice = token.priceData[0];
      
      return {
        id: token.id,
        symbol: token.symbol,
        name: token.name,
        chain: token.chain,
        contractAddress: token.contractAddress,
        price: latestPrice?.price || null,
        marketCap: latestPrice?.marketCap || null,
        volume24h: null, // 暂时设为null，等WebSocket更新
        priceChange24h: null, // 暂时设为null，等WebSocket更新
        rsi: latestPrice?.rsi || null,
        lastUpdated: latestPrice?.timestamp?.toISOString() || new Date().toISOString(),
        strategy: token.strategy
      };
    });

    console.log(`API返回${tokensWithPrice.length}个代币`);
    return NextResponse.json(tokensWithPrice);
  } catch (error) {
    console.error('获取代币列表失败:', error);
    return NextResponse.json({ error: '获取代币列表失败' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { symbol, name, chain, contractAddress, decimals } = body;

    if (!symbol || !name || !chain || !contractAddress) {
      return NextResponse.json({ error: '缺少必要参数' }, { status: 400 });
    }

    const token = await prisma.memeToken.create({
      data: {
        symbol,
        name,
        chain,
        contractAddress,
        decimals: decimals || 18
      }
    });

    return NextResponse.json(token);
  } catch (error) {
    console.error('创建代币失败:', error);
    return NextResponse.json({ error: '创建代币失败' }, { status: 500 });
  }
}
